<template>
  <el-menu
    :default-active="menuDefaultActive"
    :default-openeds="menuDefaultOpeneds"
    router
  >
    <template v-for="(item, index) in renderMenu">
      <el-sub-menu
        :key="index"
        :index="item.route"
        v-if="item.children && item.isMenu"
      >
        <template #title>
          <el-icon>
            <icon-menu />
          </el-icon>
          <span>{{ item.title }}</span>
        </template>
        <template v-for="(_item, _index) in item.children" :key="_index">
          <el-menu-item :index="_item.route" v-if="!!_item.isMenu">
            <el-icon>
              <document />
            </el-icon>
            <span>{{ _item.title }}</span>
          </el-menu-item>
        </template>
      </el-sub-menu>
      <el-menu-item :index="item.route" v-else-if="item.isMenu">
        <el-icon>
          <document />
        </el-icon>
        <span>{{ item.title }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { Document, Menu as IconMenu } from '@element-plus/icons-vue';

import { useAuthStore } from '@/stores/auth';
const { routes } = storeToRefs(useAuthStore());

import { useRoute } from 'vue-router';
const route = useRoute();

// 默认选中的菜单
const menuDefaultActive = ref<string>('');

// 默认展开的菜单
const menuDefaultOpeneds = ref<string[]>([]);

const renderMenu = computed((): API.auth.RouteSchema[] => {
  // 添加默认菜单
  const menus: API.auth.RouteSchema[] = [
    {
      id: 0,
      pid: 0,
      title: '控制台',
      name: 'dashboard',
      type: '1',
      isMenu: 1,
      route: '/dashboard',
      sort: 0
    }
  ];
  return menus.concat(routes.value || []);
});

onMounted(() => {
  menuDefaultActive.value = route.path;
});
</script>

<style lang="scss" scoped>
.el-menu {
  border-right: none;
  background-color: transparent;

  :deep(.el-menu) {
    background-color: transparent;
  }
}
</style>
